package com.yoomiito.app.address;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.CheckUtil;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.inputfilter.TextInputFilter;
import com.yoomiito.app.widget.SelectView;
import com.yoomiito.app.widget.dialog.CustomDialog1;
import com.yoomiito.app.widget.dialog.TipDialog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import cn.droidlover.xdroidmvp.cache.SharedPref;

/**
 * 编辑地址
 */
public class EditAddressActivity extends BaseActivity<EditAddressPresenter> {

    @BindView(R.id.act_add_address_receiver_name)
    EditText nameEt;
    @BindView(R.id.act_add_address_contact_num)
    EditText telEt;
    @BindView(R.id.act_add_address_street_num)
    EditText streetNumEt;
    @BindView(R.id.act_add_address_show_area)
    EditText showAreaEt;
    @BindView(R.id.act_add_address_save)
    Button saveAddress;
    @BindView(R.id.delAddress)
    TextView delAddressTv;
    @BindView(R.id.setDefaultAddress)
    SelectView setDefaultAddressView;
    private String address;
    private AddressInfo mAddressInfo;
    private BottomDialog dialog;
    private String addressData;
    private int mRequestCode = -1;

    private CustomDialog1 mCustomDialog;

    @Override
    public int getLayoutId() {
        return R.layout.act_add_address;
    }

    @Override
    public EditAddressPresenter newP() {
        return new EditAddressPresenter(App.mAppConfig);
    }

    public static void start(Context context, AddressInfo addressInfo) {
        Intent intent = new Intent(context, EditAddressActivity.class);
        intent.putExtra(Constant.DATA, addressInfo);
        context.startActivity(intent);
    }

    public static void start(Activity context, AddressInfo addressInfo, int requestCode) {
        Intent intent = new Intent(context, EditAddressActivity.class);
        intent.putExtra(Constant.DATA, addressInfo);
        intent.putExtra(Const.RequestCode.REQUESTCODE, requestCode);
        context.startActivityForResult(intent, requestCode);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        mRequestCode = intent.getIntExtra(Const.RequestCode.REQUESTCODE, -1);
        nameEt.setFilters(new InputFilter[]{new TextInputFilter().setLength(7)});
        streetNumEt.setFilters(new InputFilter[]{new TextInputFilter().setLength(60)});

        mAddressInfo = (AddressInfo) intent.getSerializableExtra(Constant.DATA);
        GradientDrawable drawable = ColorUtils.INSTANCE.gradient("#FF246C", "#FF035B", GradientDrawable.Orientation.LEFT_RIGHT);
        drawable.setCornerRadius(DensityUtil.dp2px(23));
        saveAddress.setBackground(drawable);

        if (mAddressInfo == null) {
            mAddressInfo = new AddressInfo();
        } else {
            nameEt.setText(mAddressInfo.getUserName());
            telEt.setText(mAddressInfo.getMobile());
            showAreaEt.setText(mAddressInfo.getProvinceName() + mAddressInfo.getCityName() + mAddressInfo.getCountyName());
            streetNumEt.setText(mAddressInfo.getAddress());
            delAddressTv.setVisibility(View.VISIBLE);
            setDefaultAddressView.setSelect("1".equals(mAddressInfo.getIsDefault()));
        }
        if ("1".equals(mAddressInfo.getSelect()) && mAddressInfo.isShowCheckBox()) {
            delAddressTv.setVisibility(View.INVISIBLE);
        }
        addressData = SharedPref.getInstance(App.getInstance()).getString(Constant.AddressInfo, "");
        if (TextUtils.isEmpty(addressData)) {
            getP().getConfig();
        }
        //不可编辑 不可粘贴
        showAreaEt.setFocusable(false);
        showAreaEt.setFocusableInTouchMode(false);
        showAreaEt.setKeyListener(null);
    }

    @OnClick({R.id.act_edit_address_back, R.id.delAddress, R.id.act_add_address_show_area, R.id.act_add_address_save, R.id.openTelBook})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_edit_address_back:
                finish();
                break;
            case R.id.delAddress:
                showDialog();
                break;
            case R.id.openTelBook:
                final String[] permissions = {Manifest.permission.READ_CONTACTS};
                StringBuilder sb = null;
                for (String permission : permissions) {
                    if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                        if (sb == null) {
                            sb = new StringBuilder();
                        }
                        String str = AllUtils.permissionTipMap(permission);
                        if (sb.indexOf(str) == -1) {
                            if (!TextUtils.isEmpty(sb)) {
                                sb.append("\n\n");
                            }
                            sb.append(str);
                        }
                    }
                }
                if (sb == null || TextUtils.isEmpty(sb)) {
                    AllUtils.requestPermission2(this, Manifest.permission.READ_CONTACTS)
                            .subscribe(permission -> {
                                if (permission.granted) {
                                    Intent intent = new Intent();
                                    intent.setAction("android.intent.action.PICK");
                                    intent.addCategory("android.intent.category.DEFAULT");
                                    intent.setType("vnd.android.cursor.dir/phone_v2");
                                    startActivityForResult(intent, 1);
                                }else if (permission.shouldShowRequestPermissionRationale){

                                }else {//选中不再询问
                                    TipDialog tipDialog = new TipDialog(this);
                                    tipDialog.setCancelText("取消");
                                    tipDialog.setSureText("去开启");
                                    tipDialog.setContent("开启通讯录权限才能从通讯录中选择");
                                    tipDialog.setTitle("开启通讯录权限");
                                    tipDialog.setClickListener(v -> {
                                        /**************到系统权限设置页**********************/
                                        Intent intent = new Intent();
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        if(Build.VERSION.SDK_INT >= 9){
                                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                            intent.setData(Uri.fromParts("package", getPackageName(), null));
                                        } else if(Build.VERSION.SDK_INT <= 8){
                                            intent.setAction(Intent.ACTION_VIEW);
                                            intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
                                            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                                        }
                                        startActivity(intent);
                                        tipDialog.dismiss();
                                    });
                                    tipDialog.show();
                                }
                            });
                }else {
                    if (mCustomDialog == null) {
                        mCustomDialog = new CustomDialog1(this, () -> {
                            AllUtils.requestPermission2(this, Manifest.permission.READ_CONTACTS)
                                    .subscribe(permission -> {
                                        if (permission.granted) {
                                            Intent intent = new Intent();
                                            intent.setAction("android.intent.action.PICK");
                                            intent.addCategory("android.intent.category.DEFAULT");
                                            intent.setType("vnd.android.cursor.dir/phone_v2");
                                            startActivityForResult(intent, 1);
                                        }else if (permission.shouldShowRequestPermissionRationale){

                                        }else {//选中不再询问
                                            TipDialog tipDialog = new TipDialog(this);
                                            tipDialog.setCancelText("取消");
                                            tipDialog.setSureText("去开启");
                                            tipDialog.setContent("开启通讯录权限才能从通讯录中选择");
                                            tipDialog.setTitle("开启通讯录权限");
                                            tipDialog.setClickListener(v -> {
                                                /**************到系统权限设置页**********************/
                                                Intent intent = new Intent();
                                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                if(Build.VERSION.SDK_INT >= 9){
                                                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                                                } else if(Build.VERSION.SDK_INT <= 8){
                                                    intent.setAction(Intent.ACTION_VIEW);
                                                    intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
                                                    intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                                                }
                                                startActivity(intent);
                                                tipDialog.dismiss();
                                            });
                                            tipDialog.show();
                                        }
                                    });
                        });
                    }
                    mCustomDialog.setContent(String.valueOf(sb));
                    mCustomDialog.show();
                }









                break;
            case R.id.act_add_address_show_area:
                if (dialog == null) {
                    dialog = new BottomDialog(this);
                    if (TextUtils.isEmpty(addressData)) {
                        addressData = SharedPref.getInstance(App.getInstance()).getString(Constant.AddressInfo, "");
                    }
                    if (!TextUtils.isEmpty(addressData)) {
                        dialog.setAddressinfo(addressData);
                    }
                    dialog.setOnAddressSelectedListener((province, city, county, street) -> {
                        address = province.getName() + city.getName() + county.getName();
                        showAreaEt.setText(address);
                        mAddressInfo.setProvinceName(province.getName());
                        mAddressInfo.setProvinceCode(province.getCode());
                        mAddressInfo.setCityName(city.getName());
                        mAddressInfo.setCityCode(city.getCode());
                        mAddressInfo.setCountyName(county.getName());
                        mAddressInfo.setCountyCode(county.getCode());
                        mAddressInfo.setAreaName(province.getName()+city.getName()+county.getName());
                        dialog.dismiss();
                    });
                }
                dialog.show();
                break;
            case R.id.act_add_address_save:
                String name = nameEt.getText().toString().trim();
                String tel = telEt.getText().toString().trim();
                String detailAddress = streetNumEt.getText().toString().trim();
                String address = showAreaEt.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    showToast("姓名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tel)) {
                    showToast("手机号码不能为空");
                    return;
                }
                if (!CheckUtil.isMobileNO(tel)) {
                    showToast("手机号码格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    showToast("所在地区不能为空");
                    return;
                }
                if (TextUtils.isEmpty(detailAddress)) {
                    showToast("地址详情不能为空");
                    return;
                }
                mAddressInfo.setUserName(name);
                mAddressInfo.setMobile(tel);
                mAddressInfo.setAddress(detailAddress);
                mAddressInfo.setIsDefault(setDefaultAddressView.isSelected() ? "1" : "0");
                showLoading();
                if (TextUtils.isEmpty(mAddressInfo.getId())) {
                    getP().addAddress(mAddressInfo);
                } else {
                    getP().updateAddress(mAddressInfo);
                }
                break;
        }
    }

    private void showDialog() {
        TipDialog tipDialog = new TipDialog(this);
        tipDialog.setCancelText("取消");
        tipDialog.setSureText("确定删除");
        tipDialog.setContent("地址删除后不可恢复，请谨慎操作");
        tipDialog.setTitle("确认删除地址");
        tipDialog.setClickListener(v -> {
            getP().delAddress(mAddressInfo.getId());
        });
        tipDialog.show();
    }

    public void success(AddressInfo addressInfo) {
        dismissLoading();
        if (mRequestCode == -1) {//没有请求码
            toList();
        } else {
            toBack(addressInfo);
        }
    }

    private void toList() {
        EventMessage eventMessage = new EventMessage();
        eventMessage.setEventType(Type.EventMsgType.UPDATE_ADDRESS);
        EventBus.getDefault().post(eventMessage);
        finish();
    }

    private void toBack(AddressInfo addressInfo) {
        mAddressInfo.setSelect("1");
        Intent intent = new Intent();
        intent.putExtra(Constant.DATA, addressInfo);
        setResult(0, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                String phoneNum = null;
                String contactName = null;
                // 创建内容解析者
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = null;
                if (uri != null) {
                    cursor = contentResolver.query(uri,
                            new String[]{"display_name", "data1"}, null, null, null);
                }
                while (cursor.moveToNext()) {
                    contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                cursor.close();
                //  把电话号码中的  -  符号 替换成空格
                if (phoneNum != null) {
                    phoneNum = phoneNum.replaceAll("-", " ");
                    // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
                    phoneNum = phoneNum.replaceAll(" ", "");
                }
                if (contactName != null) {
                    nameEt.setText(contactName.length() > 7 ? contactName.substring(0, 7) : contactName);
                }
                telEt.setText(phoneNum);
            }
        }
    }
}
